import React, { Component } from 'react'
import { Modal, Form, Input } from 'antd'

import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig.js'

import MultiColumnInput from './multiColumnInput.js'

const { TextArea } = Input
const { leagueManagement: { updatePolicy, createPolicy }} = address

class CreateModal extends Component {
  constructor(props) {
    super(props)
    this.state = {
      content: '',
      updateId: '',
      status: 'create', // create/update
    }
  }

  componentDidMount() {
    const { data } = this.props
    if (data) {
      this.setState({
        content: data.content,
        updateId: data.id,
        status: 'update',
      })
    }
  }

  handleOk = () => {
    this.form.submit()
  }

  handleCancel = () => {
    this.props.createCerClose(false)
  }

  submitForm = (values) => {
    const { orgList } = this.props
    const _this = this
    const orgNames = [...new Set((values.content || []).reduce((arr, v) => {
      return arr.concat(v.children)
    }, []))]
    const orgIds = orgList.filter(v => orgNames.includes(v.name)).map(v => v.id)
    let content = this.formatContentFn(values.content || [])
    const consortiumId = this.props.match.params.id
    values.content = content
    let options = {
      ...values,
      consortiumId,
      orgIds,
    }
    if (this.state.status === 'update') {
      options.id = this.state.updateId
      request().put(updatePolicy, options).then(res => {
        if (res.status === 200) {
          _this.props.createCerClose(true)
        }
      })
    } else {
      request().post(createPolicy, options).then(res => {
        if (res.status === 200) {
          _this.props.createCerClose(true)
        }
      })
    }
  }

  formatContentFn = (data) => {
    let result = ''
    if (!data) return false
    if (data.length === 1) {
      // 没有OR关系
      let arr = data[0].children
      let sss = arr.length && arr.filter(k => k !== false).map(item => {
        item = ("'" + item + 'MSP.peer' + "'")
        return item
      })
      result = sss.length ? 'AND('.concat(sss.join(', ').toString().concat(')')) : ''
    } else {
      // 有OR关系
      let allPeers = ''
      const _data = data.length && data.filter(j => j.children.length > 0) || []
      _data.length && _data.forEach((item, idx) => {
        let arr = item.children || []
        const _arr = arr.filter(k => k !== false)
        if (_arr.length > 0) {
          let sss = _arr.map(item => {
            item = ("'" + item + 'MSP.peer' + "'")
            return item
          })
          let peers = sss.length ? 'AND('.concat(sss.join(', ').toString().concat(')')) : ''
          if (idx === _data.length - 1) {
            allPeers += peers
          } else {
            allPeers += peers + ',  '
          }
        }
      })
      result = allPeers ? 'OR(' + allPeers + ')' : ''
    }

    return result
  }

  render() {
    const { content, status } = this.state
    const { props } = this
    const _this = this
    return (
      <Modal
        width={719}
        getContainer={() => document.getElementById('policy-page')}
        className="create-p-modal common-normal-modal"
        title="新增策略"
        visible={this.props.visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        cancelText={'取消'}
        okText={'确认'}
        style={{ top: '158px' }}
      >
        <Form onFinish={this.submitForm} initialValues={this.props.data} ref={(ref) => (this.form = ref)} className="create-form">
          <Form.Item
            label="策略名称"
            name="name"
            rules={[{ required: true, message: '请输入策略名称' }]}
          >
            <Input maxLength={15} autoComplete="off" placeholder="请输入策略名称" />
          </Form.Item>
          <Form.Item
            label="策略描述"
            name="description"
            rules={[{ required: true, message: '请输入策略描述' }]}
          >
            <TextArea rows={5} maxLength={100} placeholder="请输入策略描述" />
          </Form.Item>
          <Form.Item
            label="策略内容"
            name="content"
            rules={
              status === 'create'
                ? [{ required: true, message: '请输入策略内容' }]
                : [
                  { required: true, message: '请输入策略内容' },
                  () => ({
                    validator(rule, value) {
                      if (_this.formatContentFn(value)) {
                        return Promise.resolve()
                      }
                      return Promise.reject('请输入策略内容')
                    },
                  }),
                ]

            }

          >
            <MultiColumnInput content={content} {...props} _this={this}
            />
          </Form.Item>
        </Form>

      </Modal>
    )
  }
}

export default CreateModal
